package com.itheima.app.manager;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.aip.AipFaceTemplate;
import com.itheima.autoconfig.im.HuanXinTemplate;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.autoconfig.sms.SmsTemplate;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.vo.ErrorResult;
import com.itheima.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Component
public class UserManager {

    @DubboReference
    UserService userService;

    @Autowired
    SmsTemplate smsTemplate;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @DubboReference
    UserInfoService userInfoService;

    @Autowired
    AipFaceTemplate aipFaceTemplate;

    @Autowired
    OssTemplate ossTemplate;

    @Autowired
    HuanXinTemplate huanXinTemplate;
    public Long save(User user) {
        //设置一个初始化密码
        user.setPassword(ConstantUtil.INIT_PASSWORD);
        return userService.save(user);
    }

    public User findByMobile(String mobile) {
        return userService.findByMobile(mobile);
    }

    //发送验证码
    public void sendCode(String phone) {
        //1.生成随机验证码
        String code = RandomUtil.randomNumbers(6);

        // TODO 以后项目上线了,删除
        code = "123456";
        //2.调用阿里云模板发送短信
        // TODO 以后项目上线了,开启注释
        //smsTemplate.sendSms(phone,code);

        //3.将验证码保存到redis中,时效5分钟
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE + phone, code, Duration.ofMinutes(5));
    }

    //注册或登录
    public ResponseEntity regAndLogin(Map<String, String> map) {
        //1.获取用户提交过来的手机号和验证码
        String phone = map.get("phone");
        String verificationCode = map.get("verificationCode");

        //2.判断验证码是否和redis中的一致,若不一致,返回错误提示500
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String redisCode = operations.get(ConstantUtil.SMS_CODE + phone);

        //使用hutools
        if (!StrUtil.equals(verificationCode, redisCode)) {
            return ResponseEntity.status(500).body(ErrorResult.loginError());
        }

        //3.远程调用service,查询手机号是否存在
        User user = userService.findByMobile(phone);

        //3.1 若存在,isNew=false
        boolean isNew;
        if (user != null) {
            isNew = false;
        } else {
            //3.2 若不存在,isNew=true,是新用户,调用service完成保存操作
            isNew = true;

            user = new User();
            user.setMobile(phone);
            user.setPassword(ConstantUtil.INIT_PASSWORD);

            Long id = userService.save(user);
            //别忘记给用户设置id
            user.setId(id);

            //往环信上注册
            huanXinTemplate.register("HX"+id);
        }

        //4.准备用户数据(id,手机号),生成token
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("id", user.getId());
        userMap.put("phone", user.getMobile());

        String token = JwtUtil.createToken(userMap);

        //5.为了避免每次都解析token,将token作为key,用户的json数据做为value,放入redis中
        operations.set(ConstantUtil.USER_TOKEN + token, JSON.toJSONString(user), Duration.ofDays(30));

        //6.准备返回的数据
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", token);
        resultMap.put("isNew", isNew);

        //7.把验证码删除一下
        stringRedisTemplate.delete(ConstantUtil.SMS_CODE);

        return ResponseEntity.ok(resultMap);
    }

    //完善用户基本资料
    public ResponseEntity saveUserInfo(UserInfo userInfo, String token) {
        //1.从token中获取当前登录者
        User user = getUserFromToken(token);

        //2.判断登录者是否为空,若为空,返回401
        if (user == null) {
            return ResponseEntity.status(401).body(null);
        }

        //3.给userInfo设置用户id
        userInfo.setId(user.getId());

        //4.远程调用service完成保存操作
        userInfoService.save(userInfo);
        return ResponseEntity.ok(null);
    }

    //从token中获取用户信息
    public User getUserFromToken(String token) {
        if (StrUtil.isNotBlank(token)) {
            String userJson = stringRedisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + token);
            if (StrUtil.isNotBlank(userJson)) {
                return JSON.parseObject(userJson, User.class);
            }
        }
        return null;
    }

    // 完善用户头像
    public ResponseEntity saveUserInfoHead(MultipartFile headPhoto, String token) throws IOException {
        //1.从token中获取用户
        //User user = getUserFromToken(token);
        //2.判断用户是否存在,若不存在返回401
        //if (user == null) {
        //     return ResponseEntity.status(401).body(null);
        //}
        User user = UserHolder.get();

        //3.先判断用户头像是否为人脸,若不是返回错误
        if (!aipFaceTemplate.detect(headPhoto.getBytes())) {
            return ResponseEntity.status(500).body(ErrorResult.faceError());
        }

        //4.将用户头像保存到oss上,返回url
        String url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        //5.创建一个UserInfo,设置id和头像
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setAvatar(url);//头像
        userInfo.setCoverPic(url);//封面

        //6.远程调用service完成更新操作
        userInfoService.update(userInfo);
        return ResponseEntity.ok(null);
    }

    //获取用户基本信息
    public ResponseEntity findUserInfoById(Long id) {
        //1.远程调用service查询userInfo
        UserInfo userInfo = userInfoService.findById(id);
        //2.创建UserInfoVo对象
        UserInfoVo vo = new UserInfoVo();
        //3.属性拷贝
        BeanUtil.copyProperties(userInfo, vo);
        //4.返回userInfo
        return ResponseEntity.ok(vo);
    }

    //修改用户信息
    public ResponseEntity updateUserInfo(UserInfo userInfo, String token) {
        //1.从token中获取用户
        //User user = getUserFromToken(token);
        //2.判断用户是否存在,若不存在返回401
        //if (user == null) {
        //     return ResponseEntity.status(401).body(null);
        //}

        User user = UserHolder.get();
        //3.给userInfo设置id
        userInfo.setId(user.getId());

        //4.远程调用service完成更新
        userInfoService.update(userInfo);
        return ResponseEntity.ok(null);
    }
}
